package com.durian.base.utils;

import android.os.SystemClock;

/**
 * 说明：获取服务器时间
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2018/8/4 16:57
 * <p/>
 * 版本：version 1.0
 */
public class ServerTime {

    private static final String TAG = "ServerTime";
    private static ServerTime serverTimeUtils = new ServerTime();
    private boolean isInit = false;
    private static SPUtils mSp = SPUtils.get("ServerTime_9527");
    private static String KEY_CURRENT_TIME = "KEY_CURRENT_TIME";
    private static String KEY_FIRST_BOOT_TIME = "KEY_FIRST_BOOT_TIME";

    private ServerTime(){}

    public static ServerTime getInstance(){
        return serverTimeUtils;
    }

    public boolean isInit(){
        return mSp.readLong(KEY_CURRENT_TIME,0) != 0;
    }

    public synchronized void init(long currentTime){
        if (!isInit){
            long firstBootTime = SystemClock.elapsedRealtime();
            mSp.write(KEY_CURRENT_TIME,currentTime);
            mSp.write(KEY_FIRST_BOOT_TIME,firstBootTime);
            isInit = true;
        }
    }

    public String getTime(String format){
        String time = "";
        try {
            time =  DateUtils.getLongToStr(getMillSeconds(),format);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (StringUtils.isEmpty(time)){
                time = DateUtils.getNowTime(format);
            }
        }
        return time;
    }

    public long getMillSeconds(){
        if (isInit){
            long currentTime = mSp.readLong(KEY_CURRENT_TIME);
            long first = mSp.readLong(KEY_FIRST_BOOT_TIME);
            long second = SystemClock.elapsedRealtime();
            LogUtils.e(TAG,"获取服务器时间"+currentTime + (second - first));
            return currentTime + (second - first);
        }else {
            LogUtils.e(TAG,"获取系统时间"+DateUtils.getMillisecond());
            return DateUtils.getMillisecond();
        }
    }
}
